import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Table, Modal,Form,Drawer,Button,Select, message} from 'antd';
import {getAllBkList,getBkStockList,updateBkJd } from '../../service/apis/monitor';
import { BKJD,YQ } from '../../service/config';
import './index.css';
import { StockType } from '../../service/config';

const BanKuai: React.FC = () => {
  
  const [tableData, setTableData] = useState([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerData, setDrawerData] = useState([]);
  const [dayCount, setDayCount] = useState(5);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState(null);
  const [form] = Form.useForm();

  const jdEnumToChinese = (jd) => {
    return BKJD[jd] || jd;
  };

  const yqEnumToChinese = (yq) => {
    return YQ[yq] || yq;
  };

  useEffect(() => {
    fetchTableData(dayCount);
  }, [dayCount]);

  const fetchTableData = (count) => {
    getAllBkList({ count }).then(data => {
      setTableData(data.map(item => ({
        name: item.name, // 显示 name + code
        code: item.code,
        jyr: new Date(item.jyr).toISOString().slice(0, 10), // 转换为 YYYY-MM-DD 格式
        jd: item.jd,
        qd: item.qd,
        yq: item.yq,
        zdt: `${item.ztNum}/${item.dtNum}`,
        zqxy: `${Number(item.kpYj ||0).toFixed(2)}/${Number(item.kpZqxy ||0).toFixed(2)}/${Number(item.zqxy ||0).toFixed(2)}/${Number(item.kqxy ||0).toFixed(2)}`,
        highZqxy: `${Number(item.highKpYj ||0).toFixed(2)}/${Number(item.highKpZqxy ||0).toFixed(2)}/${Number(item.highZrdbZqxy ||0).toFixed(2)}/${Number(item.highKqxy ||0).toFixed(2)}`,
        totalMonitor: item.totalMonitor,
      })));
      message.success('获取板块数据成功');
    });
  };

  const dayChangeClick = (value) => {
    setDayCount(value);
    fetchTableData(value);
  }
  const handleTotalMonitorClick = (record) => {
    getBkStockList({ jyr: record.jyr, bkcode: record.code }).then(data => {
      debugger;
      setDrawerData(data);
      setDrawerVisible(true);
    });
  };

  const renderColoredText = (text) => {
    const value = parseFloat(text);
    const color = value > 0 ? '#cf1322' : value < 0 ? '#3f8600' : 'inherit';
    return <span style={{ color }}>{text}</span>;
  };
  const handleSetNode = (record) => {
    setSelectedRecord(record);
    setIsModalVisible(true);
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      // 更新节点逻辑
      const updatedTableData = tableData.map(item => {
        debugger;
        if (item.code === selectedRecord.code && item.jyr === selectedRecord.jyr) {
          return { ...item, jd: values.jd,yq: values.yq };
        }
        return item;
      });
      updateBkJd({ jyr: selectedRecord.jyr, bkcode: selectedRecord.code,jd: values.jd,yq: values.yq });
      setTableData(updatedTableData);
      setIsModalVisible(false);
      message.success('设置成功');
    }).catch(info => {
      console.log('验证失败:', info);
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const columns = [
    {
      title: '板块名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      render: (text, row, index) => {
        const obj = {
          children: `${text}`,
          props: {},
        };
        if (index > 0 && text === tableData[index - 1].name) {
          obj.props.rowSpan = 0;
        } else {
          let rowSpan = 1;
          for (let i = index + 1; i < tableData.length; i++) {
            if (tableData[i].name === text) {
              rowSpan++;
            } else {
              break;
            }
          }
          obj.props.rowSpan = rowSpan;
        }
        return obj;
      },
    },
    {
      title: '交易日',
      dataIndex: 'jyr',
      key: 'jyr',
      align: 'center',
    },
    {
      title: '节点',
      dataIndex: 'jd',
      key: 'jd',
      align: 'center',
      render: (text, record) => (
        text ? jdEnumToChinese(text) : <Button type="link" onClick={() => handleSetNode(record)}>设置</Button>
      ),
    },
    {
      title: '开盘预期',
      dataIndex: 'yq',
      key: 'yq',
      align: 'center',
      render: (text, record) => (
        text ? yqEnumToChinese(text) : <Button type="link" onClick={() => handleSetNode(record)}>设置</Button>
      ),
    },
    {
      title: '强度',
      dataIndex: 'qd',
      key: 'qd',
      align: 'center',
    },
    {
      title: '涨跌停',
      dataIndex: 'zdt',
      key: 'zdt',
      align: 'center',
    },
    {
      title: '股票池',
      dataIndex: 'totalMonitor',
      key: 'totalMonitor',
      align: 'center',
      render: (text, record) => (
        <a onClick={() => handleTotalMonitorClick(record)}>{text}</a>
      ),
    },

    {
      title: '整体赚钱效应',
      dataIndex: 'zqxy',
      key: 'zqxy',
      align: 'center',
      render: renderColoredText,
    },
    {
      title: '高位赚钱效应',
      dataIndex: 'highZqxy',
      key: 'highZqxy',
      align: 'center',
      render: renderColoredText,
    },

  
  ];

  const drawerColumns = [
      { title: '类型', 
        dataIndex: 'type', 
        key: 'type',
        render: (text, row, index) => {
          const obj = {
            children: StockType[text] || text,
            props: {},
          };
          if (index > 0 && text === drawerData[index - 1].type) {
            obj.props.rowSpan = 0;
          } else {
            let rowSpan = 1;
            for (let i = index + 1; i < drawerData.length; i++) {
              if (drawerData[i].type === text) {
                rowSpan++;
              } else {
                break;
              }
            }
            obj.props.rowSpan = rowSpan;
          }
          return obj;
        },
      },
      { title: '代码', dataIndex: 'code', key: 'code',align: 'center',
        render: (text: string, record: any) => (
          <div>
              <Button type="link">
                {record.code}
              </Button>
          </div>
        ),  
      },
      { title: '名称', dataIndex: 'name', key: 'name',align: 'center'},
      { title: '涨幅', dataIndex: 'zqxy', key: 'zqxy' ,align: 'center'},
      { title: '低位', dataIndex: 'sort', key: 'sort' ,align: 'center'},
      { title: '连扳描述', dataIndex: 'lbDesc', key: 'lbDesc' ,align: 'center'}
    ];

  return (
    <div>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card title="板块数据">
            <div style={{ marginBottom: '16px' }}>
              <Button type={dayCount === 5 ? 'primary' : 'default'} onClick={() => dayChangeClick(5)} style={{ marginRight: '8px' }}>
                5日数据
              </Button>
              <Button type={dayCount === 10 ? 'primary' : 'default'} onClick={() => dayChangeClick(10)}>
                10日数据
              </Button>
            </div>
            <Table className="custom-table-cell" columns={columns} dataSource={tableData} pagination={false} bordered />
          </Card>
        </Col>
      </Row>
      <Drawer
      title="股票池"
      placement="right"
      onClose={() => setDrawerVisible(false)}
      visible={drawerVisible}
      width={600}
    >
      <Table className="custom-table-cell" columns={drawerColumns} dataSource={drawerData} pagination={false} />
    </Drawer>
    <Modal
        title="设置节点"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="jd"
            label="节点"
            rules={[{ required: true, message: '板块节点' }]}
          >
            <Select>
              {Object.entries(BKJD).map(([key, value]) => (
                <Option key={key} value={key}>
                  {value}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="yq"
            label="预期"
            rules={[{ required: true, message: '开盘预期' }]}
          >
            <Select>
              {Object.entries(YQ).map(([key, value]) => (
                <Option key={key} value={key}>
                  {value}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BanKuai;